/**
 * 粘性侧边导航栏JavaScript功能
 * 独立命名空间，不影响现有页面功能
 * 基于Intersection Observer实现滚动高亮
 */

window.StickyNav = (function() {
    'use strict';

    // 配置选项
    const config = {
        containerSelector: '.sticky-nav-container',
        linkSelector: '.sticky-nav__link',
        sectionSelector: '[data-category-id]',
        activeClass: 'sticky-nav__link--active',
        visibleClass: 'sticky-nav-visible',
        offsetTop: 100, // 滚动偏移量
        debounceDelay: 100, // 防抖延迟
        showDelay: 1000 // 页面加载后显示延迟
    };

    // 状态管理
    let state = {
        isInitialized: false,
        observer: null,
        currentActiveId: null,
        sections: [],
        navLinks: [],
        container: null,
        isUserClick: false, // 标记是否为用户点击
        lastClickTime: 0, // 上次点击时间
        updateTimer: null // 防抖更新定时器
    };

    /**
     * 初始化粘性导航
     */
    function init() {
        if (state.isInitialized) return;

        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initialize);
        } else {
            initialize();
        }
    }

    /**
     * 初始化执行函数
     */
    function initialize() {
        // 获取DOM元素
        state.container = document.querySelector(config.containerSelector);
        state.navLinks = document.querySelectorAll(config.linkSelector);
        // 专门查找分类区域，使用data-category-id属性
        state.sections = document.querySelectorAll('.category-section[data-category-id]');

        if (!state.container || state.navLinks.length === 0 || state.sections.length === 0) {
            console.warn('StickyNav: 必要的DOM元素未找到');
            return;
        }

        // 绑定事件
        bindEvents();

        // 设置Intersection Observer
        setupIntersectionObserver();

        // 延迟显示导航
        setTimeout(() => {
            state.container.classList.add(config.visibleClass);
        }, config.showDelay);

        state.isInitialized = true;
        console.log('StickyNav: 初始化完成');
        console.log('找到导航链接数量:', state.navLinks.length);
        console.log('找到分类区域数量:', state.sections.length);
        console.log('导航链接示例:', state.navLinks[0]);
        console.log('分类区域示例:', state.sections[0]);
    }

    /**
     * 绑定事件监听器
     */
    function bindEvents() {
        // 导航链接点击事件
        state.navLinks.forEach(link => {
            link.addEventListener('click', handleNavClick);
        });

        // 页面滚动事件（带防抖）
        let scrollTimeout;
        window.addEventListener('scroll', () => {
            clearTimeout(scrollTimeout);
            scrollTimeout = setTimeout(handleScroll, config.debounceDelay);
        });

        // 窗口大小变化事件
        window.addEventListener('resize', debounce(handleResize, 250));
    }

    /**
     * 处理导航链接点击
     */
    function handleNavClick(event) {
        event.preventDefault();

        const link = event.currentTarget;
        const targetId = link.getAttribute('href');

        console.log('点击导航链接:', targetId); // 调试日志

        if (!targetId || targetId === '#') return;

        // 设置用户点击标记和时间
        state.isUserClick = true;
        state.lastClickTime = Date.now();

        // 立即更新激活状态
        updateActiveNavItem(targetId);

        // 平滑滚动到目标区域 - 使用data-category-id属性查找
        const categoryId = targetId.replace('#category-', '');
        let targetElement = document.querySelector(`.category-section[data-category-id="${categoryId}"]`);
        if (!targetElement) {
            targetElement = document.querySelector(targetId);
        }
        console.log('查找分类ID:', categoryId); // 调试日志
        console.log('找到目标元素:', targetElement); // 调试日志

        if (targetElement) {
            console.log('目标元素位置:', targetElement.offsetTop); // 调试日志
            const offsetTop = targetElement.offsetTop - config.offsetTop;
            window.scrollTo({
                top: offsetTop,
                behavior: 'smooth'
            });
        } else {
            console.warn('未找到目标元素:', targetId);
        }

        // 滚动完成后重置用户点击标记
        setTimeout(() => {
            state.isUserClick = false;
        }, 1000); // 1秒后重置，确保滚动完成
    }

    /**
     * 设置Intersection Observer
     */
    function setupIntersectionObserver() {
        const observerOptions = {
            root: null,
            rootMargin: `-${config.offsetTop}px 0px -50% 0px`,
            threshold: [0, 0.1, 0.2, 0.5, 1]
        };

        state.observer = new IntersectionObserver((entries) => {
            handleIntersection(entries);
        }, observerOptions);

        // 观察所有分类区域 - 使用data-category-id属性
        document.querySelectorAll('.category-section[data-category-id]').forEach(section => {
            state.observer.observe(section);
        });
    }

    /**
     * 处理Intersection Observer回调
     */
    function handleIntersection(entries) {
        // 如果是用户点击引起的滚动，暂时忽略Intersection Observer
        if (state.isUserClick) {
            return;
        }

        let mostVisibleEntry = null;
        let maxRatio = 0;

        // 找到可见性最高的区域
        entries.forEach(entry => {
            if (entry.isIntersecting && entry.intersectionRatio > maxRatio) {
                mostVisibleEntry = entry;
                maxRatio = entry.intersectionRatio;
            }
        });

        // 更新激活状态
        if (mostVisibleEntry) {
            const categoryId = mostVisibleEntry.target.getAttribute('data-category-id');
            updateActiveNavItem(`#category-${categoryId}`);
        }
    }

    /**
     * 更新导航项激活状态
     */
    function updateActiveNavItem(targetId) {
        if (state.currentActiveId === targetId) return;

        console.log('更新激活状态:', targetId); // 调试日志

        // 使用防抖处理避免快速切换
        debouncedUpdateActive(targetId);
    }

    /**
     * 防抖更新激活状态
     */
    function debouncedUpdateActive(targetId) {
        // 清除之前的定时器
        if (state.updateTimer) {
            clearTimeout(state.updateTimer);
        }

        // 设置新的定时器
        state.updateTimer = setTimeout(() => {
            // 移除所有激活状态
            removeActiveClass();

            // 添加新的激活状态
            const activeLink = document.querySelector(`${config.linkSelector}[href="${targetId}"]`);
            if (activeLink) {
                activeLink.classList.add(config.activeClass);
                state.currentActiveId = targetId;
                console.log('成功设置激活状态:', targetId); // 调试日志
            } else {
                console.warn('未找到导航链接:', targetId); // 调试日志
            }

            state.updateTimer = null;
        }, 50); // 50ms 防抖延迟
    }

    /**
     * 移除所有激活状态
     */
    function removeActiveClass() {
        state.navLinks.forEach(link => {
            link.classList.remove(config.activeClass);
        });
        state.currentActiveId = null;
    }

    /**
     * 处理页面滚动
     */
    function handleScroll() {
        // 可以在这里添加额外的滚动逻辑
        updateScrollProgress();
    }

    /**
     * 更新滚动进度指示器
     */
    function updateScrollProgress() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
        const progress = (scrollTop / scrollHeight) * 100;

        const progressBar = state.container.querySelector('.sticky-nav__progress');
        if (progressBar) {
            progressBar.style.height = `${Math.min(progress, 100)}%`;
        }
    }

    /**
     * 处理窗口大小变化
     */
    function handleResize() {
        // 重新计算布局
        if (state.observer) {
            state.observer.disconnect();
            state.sections.forEach(section => {
                state.observer.observe(section);
            });
        }
    }

    /**
     * 滚动到指定分类
     */
    function scrollToCategory(categoryId) {
        const targetId = `#category-${categoryId}`;
        const targetElement = document.querySelector(targetId);

        if (targetElement) {
            const offsetTop = targetElement.offsetTop - config.offsetTop;
            window.scrollTo({
                top: offsetTop,
                behavior: 'smooth'
            });

            updateActiveNavItem(targetId);
        }
    }

    /**
     * 滚动到顶部
     */
    function scrollToTop() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
        removeActiveClass();
    }

    /**
     * 显示/隐藏导航
     */
    function toggle() {
        if (state.container) {
            state.container.classList.toggle(config.visibleClass);
        }
    }

    /**
     * 销毁导航
     */
    function destroy() {
        if (state.observer) {
            state.observer.disconnect();
        }

        // 移除事件监听器
        state.navLinks.forEach(link => {
            link.removeEventListener('click', handleNavClick);
        });

        // 重置状态
        state.isInitialized = false;
    }

    /**
     * 防抖函数
     */
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 公共API
    return {
        init: init,
        scrollToCategory: scrollToCategory,
        scrollToTop: scrollToTop,
        toggle: toggle,
        destroy: destroy,
        // 调试用
        getState: () => state,
        getConfig: () => config
    };
})();

// 页面加载完成后自动初始化
document.addEventListener('DOMContentLoaded', function() {
    // 确保在页面完全加载后再初始化
    setTimeout(() => {
        StickyNav.init();
    }, 500);
});